<template>
    <div class="AllUse">

    </div>
</template>
<style>
    .AllUse{
        width: 10vw;
    }
</style>
<script>
    import {mapMutations} from 'vuex'
    export default {
        name: "AllUse",
        data() {
            return {
                msg: 'hello vue',
                timer: null,
                timer2: null,
                timerInterval: 60*1000,//1分钟=60s*1000ms
                UserId :localStorage.getItem("sid")?localStorage.getItem("sid"):"",
                compassTime:'',//定时器的指南针方向值
                compassArray:[],//指南针长度3的队列
                isRemove:true,//是否在移动
                timeCompass:null,//创建的指南针定时器,
                LocType:'',

            }
        },
        created () {
            //定时器30s检查是否登录，登陆后进行全局提交
            this.timer = setInterval(()=>{this.onInterval()},this.timerInterval);
            //定时器1s发送1条数组内的数据
            this.timer2 = setInterval(() => {
                this.submitInfos()
            }, 2000);
            //用指南针判断用户是否移动。这里涉及到切换用户状态，所以先省略
            /*this.timeCompass = setInterval(this.getCompass,2000);*/
        },
        mounted(){

        },
        methods:{
            onInterval: function() {
                let me = this;
                if(localStorage.getItem("sid")) {
                    me.submitData();
                }
            },
            ...mapMutations(['updateFloodsMessage']),

            submitData() {
                // submit location info
                    let self = this;
                    let Longitude; //  = localStorage.getItem("longitude")?localStorage.getItem("longitude"):"122.22";//经度
                    let Latitude; // = localStorage.getItem("latitude")?localStorage.getItem("latitude"):"22.22";//纬度
                    let Speed; /*= localStorage.getItem("speed")?localStorage.getItem("speed"):"0";*///速度
                    let Altitude ;
                    let Time0 = new Date();//获取当前时间
                    let Time = self.formatDate(Time0);//格式化当前时间
                    let gis4_phoneTime = Time0.getTime();//长整型当前时间
                    let UserId =localStorage.getItem("sid")?localStorage.getItem("sid"):"";
                    let WorkModeId = localStorage.getItem("workModeId")?localStorage.getItem("workModeId"):"2";
                    let failSendInfo = localStorage.getItem("failSendInfo_"+UserId)?JSON.parse(localStorage.getItem("failSendInfo_"+UserId)):[];
                    let infos = { }
                    this.$store.commit("updatePhoneTime",gis4_phoneTime);//内存保存当前时间戳


                //百度地图sdk可行 读取定位数据 保存定位信息 发送定位信息
                self.getCooUsingBaiduSdk().then(coo=>{
                    /*console.log(JSON.stringify(result, null, 4));*/
                    //console.log(coo);
                    //上一次的经纬度数据,这里为了监控在线，故取消19-07-12
                    //let oldLongitude = self.$store.state.longitude;
                    //let oldLatitude = self.$store.state.latitude;
                    Longitude = coo.Longitude;
                    Latitude = coo.Latitude;
                    Speed = coo.Speed;
                    Altitude = coo.Altitude;
                    self.LocType = coo.LocType;
                    //避免相同经纬度数据重复提交
                    //if(oldLongitude!==Longitude||oldLatitude!==Latitude){
                        self.$store.commit("updateLatitude",Latitude);//更新VueX的经纬度
                        self.$store.commit("updateLongitude",Longitude);//更新VueX的经纬度
                        //避免经纬度空数据提交
                        /*if(Longitude<0.0||Longitude>180.0){//经度最大是180° 最小是0°
                            return;
                        }else if(Latitude>90.0||Latitude<0.0){//纬度最大是90° 最小是0°
                            return;
                        }*/
                        //返回状态类型如162以上，则定位失败，不提交数据
                        if(self.LocType>161){
                            return;
                        }
                        else if(WorkModeId===""||UserId===""){
                            return;
                        }else if(self.isRemove===false){
                            return;
                        }
                        else {
                            infos.UserId = UserId;
                            infos.Time = Time;
                            infos.Longitude = Longitude;
                            infos.Latitude = Latitude;
                            infos.WorkModeId = WorkModeId;
                            infos.Speed = Speed;
                            infos.Altitude = Altitude;
                            failSendInfo.push(infos);
                            //优化版，将所得的数据放入和失败数据一个数组，每30s放一个，每秒发送一条。优先发送最新
                            //向数组的开头添加一个或更多元素，并返回新的长度。
                            localStorage.setItem("failSendInfo_"+UserId,JSON.stringify(failSendInfo));
                        }

                }).catch(err => {
                    console.log(err)
                })
            },
            getCooUsingBaiduSdk() {
                let params  = {CoorType:"gcj02",OpenAutoNotifyMode:true,Interval:3000,Distance:1};//bd09ll,gcj02,
                return new Promise((resolve, reject) => {
                    if(typeof (baidumap_location)!=="undefined"){//if判断是为了兼容浏览器调试不报错
                        baidumap_location.getCurrentPosition((result) => {
                            //console.log(result);//use test,need delete
                            //this.$store.commit("updateTest",result);//use test,need delete
                            /*console.log(`baidu coo: ${result.longitude},${result.latitude}`);*/
                            //理解resolve，将结果放入resolve作为参数传给成功回调的参数,如，if(num<=5){resolve(num);}else{reject('数字太大了');}
                            resolve({
                                Latitude: result.latitude,
                                Longitude: result.longitude,
                                Speed:result.speed,
                                Altitude:result.altitude,
                                LocType:result.locType
                            })
                        },(error) => {
                            console.log(error);
                            reject(error)
                        },params);
                    }//if end

                })
            },
            getCooUsingGaodeSdk () {
                /*
                //高德地图sdk自定义插件进行定位获取经纬度
                function successFn(success){
                    // {accuracy:550,adcode:"440305",address:"广东省深圳市南山区高新北六道10靠近兰光科技园",
                    // backtime:1559899030603,bearing: 0, city:"深圳市",citycode: "0755",country: "中国", district: "南山区", type:4,
                    // latitude:22.554149,longitude: 113.941515,poi:"兰光科技园", province:"广东省",satellites: 0,status: "定位成功", time: "1559899030136"}
                    Latitude = success.latitude;
                    Longitude = success.longitude;
                    self.$store.commit("updateLatitude",Latitude);//更新VueX的经纬度
                    self.$store.commit("updateLongitude",Longitude);//更新VueX的经纬度
                };
                function errorFn(error){
                    console.log(error);
                };
                MyGaodePlugin.getCurrentPosition(successFn,errorFn,{GpsFirst:true,LocationCacheEnable:true,HttpTimeOut:20000,Interval:2000});*/

                //下面是navigator.geolocation获取经/纬度/速度的方法
                /*let onSuccess = function(position) {
                    self.Longitude = position.coords.longitude;
                    self.Latitude = position.coords.latitude;
                    let getSpeed = position.coords.speed;
                    if(getSpeed==null||typeof (getSpeed)==="undefined"){
                        self.Speed ="0"
                    }else{
                        self.Speed = getSpeed;
                    }
                    self.$store.commit("updateLatitude",self.Latitude);//更新VueX的经纬度
                    self.$store.commit("updateLongitude",self.Longitude);//更新VueX的经纬度
                    self.$store.commit("updateSpeed",self.Speed);

                };
                let error= function(error) {
                    self.msg='code: '    + error.code    +
                        'message: ' + error.message + ' \n ';
                }
                //首先进入获取地理位置的方法maximumAge缓存，数值0费电，设置数值不超过该值会使用该缓存
                if (navigator.geolocation){
                    navigator.geolocation.getCurrentPosition(onSuccess, error,{
                        maximumAge: 3000, timeout: 5000,enableHighAccuracy: true });// maximumAge: 0, timeout: 3000,
                }else{
                    console.log("该浏览器不支持获取地理位置。");
                }*/
            },

            fetchNext (failSendInfo) {
                return  failSendInfo[(failSendInfo.length)-1];

            },
            submitInfo (next) {
                return this.$api.sendFailInfo(next.Time, next.Longitude, next.Latitude, next.Speed, next.Altitude, next.WorkModeId, next.UserId,)
            },
            submitInfos(){
                let that = this;
                let UserId = localStorage.getItem("sid")?localStorage.getItem("sid"):"";
                if(UserId===""||UserId===null){
                    return;
                }else {
                    let failSendInfo = localStorage.getItem("failSendInfo_"+UserId)?JSON.parse(localStorage.getItem("failSendInfo_"+UserId)):[];
                    let next = this.fetchNext(failSendInfo);//数组中最后一条用户数据
                    //如果下一条要提交的数据为空不提交
                    if(next == null || typeof (null) ==="undefined"){
                        return;
                    }
                    else{
                            that.submitInfo(next).then(resp => {
                                if (resp.status < 300) {
                                    failSendInfo.splice((failSendInfo.length)-1, 1);//得到用户成功发送信息后，剩下失败的信息
                                    localStorage.setItem("failSendInfo_"+UserId, JSON.stringify(failSendInfo));
                                }else{
                                    failSendInfo.unshift(next);//不成功的数据先放数组前面，再消除末尾，如1234，41234，1234
                                    failSendInfo.splice((failSendInfo.length)-1, 1);
                                    localStorage.setItem("failSendInfo_"+UserId, JSON.stringify(failSendInfo));
                                }
                            }).catch(err=> {
                                // next.error = next.error ? next.error+1: 1;
                                failSendInfo.unshift(next);//不成功的数据先放数组前面，再消除末尾
                                failSendInfo.splice((failSendInfo.length)-1, 1);
                                localStorage.setItem("failSendInfo_"+UserId, JSON.stringify(failSendInfo));
                                console.log(err);
                            });


                    }
                }

            },
            formatDate(value){
                     let year = value.getFullYear();
                     let month = value.getMonth() + 1;
                     let date = value.getDate();
                     let hour = value.getHours();
                     let minute = value.getMinutes();
                     let second = value.getSeconds();
                    return year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
            },
            //指南针计时器成功回调
            compassTimeSuccess(result){
                this.compassTime = result.magneticHeading.toFixed(2);
                if(this.compassArray.length<3){
                    this.compassArray.push(this.compassTime);//比如开始时小于3个长度未放满，则继续插入进数组
                    this.isRemove = true;
                    this.$store.commit("updateCompass",true);
                }else {
                    this.compassArray.splice(0,1);//删除第一个元素
                    this.compassArray.push(this.compassTime);
                }
                //得到诸如[213.54,213.69,213.72]
                let getDouble0Top = Math.floor(this.compassArray[0])+1;//199.00+1=120向下取整ceil120
                let getDouble0Buttom = Math.floor(this.compassArray[0])-1;//199.00-1=198.00向下取整198floor-1
                let getTotal23 = Math.floor(parseFloat(this.compassArray[1])+parseFloat(this.compassArray[2]));//第23数之和
                if(getDouble0Buttom*2 <= getTotal23 && getTotal23<= getDouble0Top*2){
                    this.isRemove = false;
                    this.$store.commit("updateCompass",false);
                }else{
                    this.isRemove = true;
                    this.$store.commit("updateCompass",true);
                }
                console.log("isRemove",this.isRemove,this.$store.state.compass);

            },
            //指南针计时器失败回调
            compassTimeError(error) {
                console.log("指南针失败回调:",error);
            },
            getCompass(){
                if(typeof (navigator.compass)!=="undefined"){
                    navigator.compass.getCurrentHeading(this.compassTimeSuccess,this.compassTimeError)
                }

            },


    },

    }
</script>

